class AdminChat {
    constructor() {
        this.socket = null;
        this.adminId = this.generateAdminId();
        this.userType = 'admin';
        this.currentUser = null;
        this.onlineUsers = new Map();
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 3000;
        
        this.initElements();
        this.initEventListeners();
        this.connectWebSocket();
    }

    generateAdminId() {
        return 'admin_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    initElements() {
        this.userList = document.getElementById('userList');
        this.onlineCount = document.getElementById('onlineCount');
        this.currentUserName = document.getElementById('currentUserName');
        this.chatMessages = document.getElementById('chatMessages');
        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
        this.charCount = document.getElementById('charCount');
        this.connectionStatus = document.getElementById('connectionStatus');
        this.statusText = this.connectionStatus.querySelector('.status-text');
        this.clearChatBtn = document.getElementById('clearChatBtn');
        this.endChatBtn = document.getElementById('endChatBtn');
        this.quickReplyBtns = document.querySelectorAll('.quick-reply-btn');
    }

    initEventListeners() {
        this.sendButton.addEventListener('click', () => this.sendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        this.messageInput.addEventListener('input', () => {
            this.updateCharCount();
            this.sendButton.disabled = !this.messageInput.value.trim() || !this.currentUser;
        });

        // 快捷回复按钮
        this.quickReplyBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const message = btn.getAttribute('data-message');
                this.messageInput.value = message;
                this.updateCharCount();
                this.sendMessage();
            });
        });

        // 清空对话
        this.clearChatBtn.addEventListener('click', () => {
            this.clearCurrentChat();
        });

        // 结束对话
        this.endChatBtn.addEventListener('click', () => {
            this.endCurrentChat();
        });

        // 页面关闭时断开连接
        window.addEventListener('beforeunload', () => {
            this.disconnect();
        });
    }

    connectWebSocket() {
        try {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/websocket/chat?userId=${this.adminId}&userType=${this.userType}`;
            
            this.socket = new WebSocket(wsUrl);
            
            this.socket.onopen = () => {
                console.log('管理员WebSocket连接已建立');
                this.reconnectAttempts = 0;
                this.updateConnectionStatus('connected', '已连接');
                this.sendJoinMessage();
            };

            this.socket.onmessage = (event) => {
                this.handleMessage(event.data);
            };

            this.socket.onclose = (event) => {
                console.log('管理员WebSocket连接已关闭', event);
                this.updateConnectionStatus('disconnected', '连接断开');
                this.handleReconnect();
            };

            this.socket.onerror = (error) => {
                console.error('管理员WebSocket错误:', error);
                this.updateConnectionStatus('disconnected', '连接错误');
                this.addSystemMessage('连接出现错误，请刷新页面重试');
            };

        } catch (error) {
            console.error('管理员WebSocket连接失败:', error);
            this.updateConnectionStatus('disconnected', '连接失败');
            this.addSystemMessage('无法连接到服务器，请稍后重试');
        }
    }

    sendJoinMessage() {
        const joinMessage = {
            type: 'join',
            userId: this.adminId,
            userType: this.userType,
            timestamp: Date.now()
        };
        this.socket.send(JSON.stringify(joinMessage));
    }

    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            
            switch (message.type) {
                case 'chat':
                    this.handleChatMessage(message);
                    break;
                case 'system':
                    this.addSystemMessage(message.content);
                    break;
                case 'userJoined':
                    this.addOnlineUser(message);
                    break;
                case 'userLeft':
                    this.removeOnlineUser(message.userId);
                    break;
                case 'userList':
                    this.updateUserList(message.users);
                    break;
            }
        } catch (error) {
            console.error('消息解析错误:', error);
        }
    }

    handleChatMessage(message) {
        // 如果是当前用户的消息，显示在聊天区域
        if (this.currentUser && message.userId === this.currentUser.userId) {
            this.addChatMessage(message);
        }
        
        // 更新用户列表中的最后消息
        this.updateUserLastMessage(message);
    }

    addOnlineUser(user) {
        this.onlineUsers.set(user.userId, {
            ...user,
            lastMessage: null,
            lastMessageTime: null
        });
        this.renderUserList();
    }

    removeOnlineUser(userId) {
        this.onlineUsers.delete(userId);
        
        // 如果当前用户离开，清空聊天区域
        if (this.currentUser && this.currentUser.userId === userId) {
            this.currentUser = null;
            this.currentUserName.textContent = '选择一个用户开始对话';
            this.clearChatMessages();
            this.disableChatInput();
        }
        
        this.renderUserList();
    }

    updateUserList(users) {
        this.onlineUsers.clear();
        users.forEach(user => {
            this.onlineUsers.set(user.userId, {
                ...user,
                lastMessage: null,
                lastMessageTime: null
            });
        });
        this.renderUserList();
    }

    updateUserLastMessage(message) {
        const user = this.onlineUsers.get(message.userId);
        if (user) {
            user.lastMessage = message.content;
            user.lastMessageTime = message.timestamp;
            this.renderUserList();
        }
    }

    renderUserList() {
        this.userList.innerHTML = '';
        this.onlineCount.textContent = this.onlineUsers.size;

        this.onlineUsers.forEach((user, userId) => {
            const userItem = document.createElement('div');
            userItem.className = 'user-item';
            if (this.currentUser && this.currentUser.userId === userId) {
                userItem.classList.add('active');
            }

            const avatar = document.createElement('div');
            avatar.className = 'user-avatar';
            avatar.textContent = user.userName ? user.userName.charAt(0).toUpperCase() : 'U';

            const userInfo = document.createElement('div');
            userInfo.className = 'user-info';

            const userName = document.createElement('div');
            userName.className = 'user-name';
            userName.textContent = user.userName || `用户${userId.slice(-6)}`;

            const status = document.createElement('div');
            status.className = 'user-status';
            status.textContent = user.lastMessage || '等待对话...';

            const time = document.createElement('div');
            time.className = 'user-time';
            time.textContent = user.lastMessageTime ? this.formatTime(user.lastMessageTime) : '';

            userInfo.appendChild(userName);
            userInfo.appendChild(status);

            userItem.appendChild(avatar);
            userItem.appendChild(userInfo);
            userItem.appendChild(time);

            userItem.addEventListener('click', () => {
                this.selectUser(user);
            });

            this.userList.appendChild(userItem);
        });
    }

    selectUser(user) {
        this.currentUser = user;
        this.currentUserName.textContent = user.userName || `用户${user.userId.slice(-6)}`;
        
        // 更新用户列表的选中状态
        document.querySelectorAll('.user-item').forEach(item => {
            item.classList.remove('active');
        });
        event.currentTarget.classList.add('active');

        // 启用聊天输入
        this.enableChatInput();
        
        // 清空并显示欢迎消息
        this.clearChatMessages();
        this.addSystemMessage(`开始与 ${user.userName || '用户'} 的对话`);
    }

    sendMessage() {
        const content = this.messageInput.value.trim();
        if (!content || !this.socket || this.socket.readyState !== WebSocket.OPEN || !this.currentUser) {
            return;
        }

        const message = {
            type: 'chat',
            userId: this.adminId,
            userType: this.userType,
            targetUserId: this.currentUser.userId,
            content: content,
            timestamp: Date.now()
        };

        this.socket.send(JSON.stringify(message));
        
        // 显示自己发送的消息
        this.addChatMessage({
            ...message,
            userId: this.adminId,
            userType: this.userType
        });

        this.messageInput.value = '';
        this.updateCharCount();
        this.sendButton.disabled = true;
    }

    addChatMessage(message) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${message.userType}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = message.content;
        
        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.formatTime(message.timestamp);
        
        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(timeDiv);
        
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    addSystemMessage(content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'system-message';
        messageDiv.innerHTML = `
            <div style="text-align: center; margin: 20px 0;">
                <span style="background: rgba(0,0,0,0.1); color: #666; padding: 8px 16px; border-radius: 12px; font-size: 12px;">
                    ${content}
                </span>
            </div>
        `;
        
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    clearCurrentChat() {
        if (this.currentUser) {
            this.clearChatMessages();
            this.addSystemMessage(`已清空与 ${this.currentUser.userName || '用户'} 的对话记录`);
        }
    }

    endCurrentChat() {
        if (this.currentUser) {
            const endMessage = {
                type: 'endChat',
                userId: this.adminId,
                targetUserId: this.currentUser.userId,
                timestamp: Date.now()
            };
            
            this.socket.send(JSON.stringify(endMessage));
            
            this.addSystemMessage(`已结束与 ${this.currentUser.userName || '用户'} 的对话`);
            
            // 移除用户
            this.onlineUsers.delete(this.currentUser.userId);
            this.renderUserList();
            
            // 重置当前用户
            this.currentUser = null;
            this.currentUserName.textContent = '选择一个用户开始对话';
            this.disableChatInput();
        }
    }

    clearChatMessages() {
        this.chatMessages.innerHTML = '';
    }

    enableChatInput() {
        this.messageInput.disabled = false;
        this.sendButton.disabled = !this.messageInput.value.trim();
        this.clearChatBtn.disabled = false;
        this.endChatBtn.disabled = false;
        this.quickReplyBtns.forEach(btn => btn.disabled = false);
    }

    disableChatInput() {
        this.messageInput.disabled = true;
        this.sendButton.disabled = true;
        this.clearChatBtn.disabled = true;
        this.endChatBtn.disabled = true;
        this.quickReplyBtns.forEach(btn => btn.disabled = true);
    }

    updateCharCount() {
        const length = this.messageInput.value.length;
        this.charCount.textContent = length;
        
        if (length > 450) {
            this.charCount.style.color = '#ef4444';
        } else if (length > 400) {
            this.charCount.style.color = '#f59e0b';
        } else {
            this.charCount.style.color = '#9ca3af';
        }
    }

    updateConnectionStatus(status, text) {
        this.connectionStatus.className = `connection-status ${status}`;
        this.statusText.textContent = text;
        
        if (status === 'connected') {
            setTimeout(() => {
                this.connectionStatus.classList.add('hidden');
            }, 2000);
        } else {
            this.connectionStatus.classList.remove('hidden');
        }
    }

    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            this.updateConnectionStatus('disconnected', `正在重连... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            
            setTimeout(() => {
                this.connectWebSocket();
            }, this.reconnectDelay);
        } else {
            this.updateConnectionStatus('disconnected', '连接失败');
            this.addSystemMessage('连接失败，请刷新页面重试');
        }
    }

    formatTime(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    }

    scrollToBottom() {
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    disconnect() {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
        }
    }
}

// 页面加载完成后初始化管理员聊天功能
document.addEventListener('DOMContentLoaded', () => {
    new AdminChat();
});